package com.study.quiz.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.study.quiz.dto.AccessTokenDTO;
import com.study.quiz.dto.GitHubUser;
import com.study.quiz.pojo.User;
import com.study.quiz.service.UserService;
import com.study.quiz.utils.ErrorIndexUtil;
import com.study.quiz.utils.GitHubHttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author CJunGod
 * @create 2020-03-03 21:26
 **/
@Slf4j
@Controller
public class AuthorizeController {

    @Resource
    private GitHubHttpUtil gitHubHttpUtil;

    @Resource
    private UserService userService;

    @Value("${github.client.id}")
    private String clientId;

    @Value("${github.client.secret}")
    private String clientSecret;

    @Value("${github.redirect.uri}")
    private String redirectUri;

    @Value("${token}")
    private String userToken;

    @Resource
    private ErrorIndexUtil errorIndexUtil;

    @GetMapping("/callback")
    public String callback(@RequestParam(name = "code") String code,
                           @RequestParam(name = "state") String state,
                           HttpServletResponse response) {
        AccessTokenDTO dto = new AccessTokenDTO(clientId, clientSecret, code, redirectUri, state);
        String accessToken = gitHubHttpUtil.getAccessToken(dto);
        GitHubUser gitHubUser = gitHubHttpUtil.getUser(accessToken);

        if (gitHubUser != null && gitHubUser.getId() != null) {

            String byAccountId = userService.findByAccountId(String.valueOf(gitHubUser.getId()));
            if (StringUtils.isNotEmpty(byAccountId)) {
                response.addCookie(new Cookie(userToken, byAccountId));
            } else {
                User user = new User();
                String token = UUID.randomUUID().toString();
                user.setName(gitHubUser.getName());
                user.setAccountId(String.valueOf(gitHubUser.getId()));
                user.setToken(token);
                user.setGmtCreate(System.currentTimeMillis());
                user.setGmtModified(user.getGmtCreate());
                user.setBio(gitHubUser.getBio());
                user.setAvatarUrl(gitHubUser.getAvatarUrl());

                userService.insert(user);
                response.addCookie(new Cookie(userToken, token));
            }

            if("1".equals(state)){
                errorIndexUtil.errorIndex("登陆成功");
                return "redirect:/";
            }else{
                errorIndexUtil.errorIndex("登陆成功");
                return "redirect:/question/"+state;
            }
        } else {
            errorIndexUtil.errorIndex("登陆失败，请联系管理员");
            return "redirect:/";
        }

    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        User user = (User) request.getSession().getAttribute("user");
        if (user != null) {
            errorIndexUtil.errorIndex("退出成功");
        } else {
            errorIndexUtil.errorIndex("当前用户未登录，请登录后重试");
        }
        request.getSession().removeAttribute("user");
        request.getSession().removeAttribute("unReadCount");
        Cookie cookie = new Cookie(userToken, null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);

        return "redirect:/";
    }
}
